package db

import (
	"github.com/xujiajun/nutsdb"
	"time"
)

const fileBucket = "file"

func InsertFile(fileType, destPath string) error {
	key := []byte(fileType + "_" + time.Now().Format("20060102150405"))
	if err := db.Update(
		func(tx *nutsdb.Tx) error {
			if err := tx.Put(fileBucket, key, []byte(destPath), 0); err != nil {
				return err
			}
			return nil
		}); err != nil {
		return err
	}
	return nil
}

func DeleteFile(entry *nutsdb.Entry) error {
	if err := db.Update(
		func(tx *nutsdb.Tx) error {
			if err := tx.Delete(fileBucket, entry.Key); err != nil {
				return err
			}
			return nil
		}); err != nil {
		return err
	}
	return nil
}

func GetAllFile() ([]*nutsdb.Entry, error) {
	result := make([]*nutsdb.Entry, 0)
	if err := db.View(
		func(tx *nutsdb.Tx) error {
			bucket := fileBucket
			entries, err := tx.GetAll(bucket)
			if err != nil {
				return err
			}

			for _, entry := range entries {
				result = append(result, entry)
			}

			return nil
		}); err != nil {
		return result, err
	}
	return result, nil
}
